package wang.Lisenter;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.ColorModel;
import java.awt.image.ImagingOpException;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;

import wang.MainFrame;
import wang.Picture;

/**
 * 
 * @author WangYi
 * 
 */

public class OpenLisenter implements ActionListener {

	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		JFileChooser jc = new JFileChooser();
		int returnValue = jc.showOpenDialog(null);
		if (returnValue == JFileChooser.APPROVE_OPTION) {
			File selectedFile = jc.getSelectedFile();
			if (selectedFile != null) {
				Picture.path=selectedFile.getParent();
				String filePath = selectedFile.getAbsolutePath();
				try {
					Picture.image = ImageIO.read(new File(filePath));
					Picture.w = Picture.image.getWidth();
					Picture.h = Picture.image.getHeight();
					Picture.orginal = getPixArray(Picture.image, Picture.w,
							Picture.h);
					Picture.gray = RGBtoGray(Picture.orginal, Picture.w,
							Picture.h);
					Picture.current =new int[Picture.w*Picture.h];

				} catch (ImagingOpException ex) {
					System.out.println(ex);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		MainFrame.showImage(Picture.originLabel, Picture.gray);
	}

	private int[] getPixArray(Image img, int width, int height) {

		int[] pixArray = new int[width * height];

		try {

			PixelGrabber pixGrb = new PixelGrabber(img, 0, 0, width, height,
					pixArray, 0, width);
			if (pixGrb.grabPixels() != true)
				try {
					throw new java.awt.AWTException("pixGrb error"
							+ pixGrb.status());
				} catch (Exception e) {
					e.printStackTrace();
				}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return pixArray;
	}

	private int[] RGBtoGray(int[] ImageSource, int w, int h) {
		int[] grayArray = new int[h * w];
		ColorModel colorModel = ColorModel.getRGBdefault();
		int i, j, k, r, g, b;
		for (i = 0; i < h; i++) {
			for (j = 0; j < w; j++) {
				k = i * w + j;
				r = colorModel.getRed(ImageSource[k]);
				g = colorModel.getGreen(ImageSource[k]);
				b = colorModel.getBlue(ImageSource[k]);
				int gray = (int) (r * 0.3 + g * 0.59 + b * 0.11);
				r = g = b = gray;
				grayArray[i * w + j] = (255 << 24) | (r << 16) | (g << 8) | b;
			}
		}
		return grayArray;
	}

}
